import React from 'react';
import { connect } from 'react-redux';
import { Form, Input, Table, message, Button } from 'antd';
import UploadVideo from 'Component/CommonComponents/UploadVideo';
import moment from 'moment/moment';
import Api from 'Utils/api';
import { formatUtcTime } from 'Utils/index';
import * as routerActions from 'react-router-redux';
import CommonBg from 'Page/DispatchPage/Components/CommonBorder';
import PicturesWall from '../../../../../UploadImage';
import UploadAudio from '../Component/UploadAudio';
import '../index.scss';

const { TextArea } = Input;
const FormItem = Form.Item;
const PAGE_SIZE = 2;
class TypicalEdit extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      id: props.params.id,
      taskId: '',
      editRecord: '',
      takInfo: {},
      orderList: [],
      feedList: [],
      planList: [],
      orderDataCount: 0,
      feedDataCount: 0,
      planDataCount: 0,
      orderListPage: 1,
      feedListPage: 1,
      planListPage: 1,
    };
    this.condition = { offset: 0, limit: PAGE_SIZE };
    this.handChange = ::this.handChange;
  }
  componentDidMount() {
    this.initList();
  }
  initTaskInfo() {
    const { taskId } = this.state;
    const api = new Api({
      method: 'GET',
      path: `/tasks/${taskId}`,
      success: (json) => {
        this.setState({
          taskInfo: json
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  initList() {
    const { id } = this.state;
    const api = new Api({
      method: 'GET',
      path: `/cases/${id}`,
      success: (json) => {
        this.setState({
          editRecord: json,
          taskId: json.task_id,
        }, () => {
          this.initOrder();
          this.initFeedback();
          this.initPlan();
          this.initTaskInfo();
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  initOrder() {
    const { taskId } = this.state;
    const api = new Api({
      method: 'GET',
      path: `/instructions/${taskId}`,
      query: { ...this.condition },
      success: (json) => {
        this.setState({
          orderList: json.data_list,
          orderListPage: ((this.condition.offset / PAGE_SIZE) + 1),
          orderDataCount: json.total_count
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  onOrderListPageChange(page) {
    this.setState({ orderListPage: page }, this.initOrder.bind(this));
    this.condition.offset = (page - 1) * PAGE_SIZE;
  }
  initFeedback() {
    const { taskId } = this.state;
    const api = new Api({
      method: 'GET',
      path: `/feedbacks/${taskId}`,
      query: { ...this.condition },
      success: (json) => {
        this.setState({
          feedList: json.data_list,
          feedListPage: ((this.condition.offset / PAGE_SIZE) + 1),
          feedDataCount: json.total_count
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  onFeedListPageChange(page) {
    this.setState({ feedListPage: page }, this.initFeedback.bind(this));
    this.condition.offset = (page - 1) * PAGE_SIZE;
  }
  initPlan() {
    const { taskId } = this.state;
    const api = new Api({
      method: 'GET',
      path: `/schemas/start/${taskId}`,
      success: (json) => {
        this.setState({
          planList: json.data_list,
          planListPage: ((this.condition.offset / PAGE_SIZE) + 1),
          planDataCount: json.total_count
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  onPlanListPageChange(page) {
    this.setState({ planListPage: page }, this.initPlan.bind(this));
    this.condition.offset = (page - 1) * PAGE_SIZE;
  }
  generatorOrderColumns() {
    return [
      {
        title: '序号',
        dataIndex: 'id',
        render: text => (
          <span >{text}</span >
        )
      },
      {
        title: '时间',
        dataIndex: 'create_time',
        render: text => (
          <span>{formatUtcTime(text)}</span>
        )
      },
      {
        title: '指令对象',
        dataIndex: 'accepter',
        render: text => (
          <span>{text}</span>
        )
      },
      {
        title: '指令内容',
        dataIndex: 'content',
        render: text => (
          <span>{text}</span>
        )
      }
    ];
  }
  generatorFeedBackColumns() {
    return [
      {
        title: '序号',
        dataIndex: 'id',
        render: text => (
          <span >{text}</span >
        )
      },
      {
        title: '时间',
        dataIndex: 'create_time',
        render: text => (
          <span>{formatUtcTime(text)}</span>
        )
      },
      {
        title: '反馈人员',
        dataIndex: 'repondent',
        render: text => (
          <span>{text}</span>
        )
      },
      {
        title: '反馈内容',
        dataIndex: 'content',
        render: text => (
          <span>{text}</span>
        )
      }
    ];
  }
  generatorPlanColumns() {
    return [
      {
        title: '序号',
        dataIndex: 'id',
        render: text => (
          <span >{text}</span >
        )
      },
      {
        title: '时间',
        dataIndex: 'create_time',
        render: text => (
          <span>{formatUtcTime(text)}</span>
        )
      },
      {
        title: '预案内容对象',
        dataIndex: 'executor',
        render: text => (
          <span>{text}</span>
        )
      },
      {
        title: '预案内容',
        dataIndex: 'title',
        render: text => (
          <span>{text}</span>
        )
      }
    ];
  }
  handCancel() {
    this.props.dispatch(routerActions.goBack());
  }
  onEnter() {
    const formValue = this.props.form.getFieldsValue();
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const api = new Api({
          method: 'PATCH',
          path: `/cases/${this.state.id}`,
          data: {
            case_name: formValue.case_name,
            task_id: this.state.taskId,
            leader: formValue.leader,
            leader_speaking: formValue.leader_speaking,
            summary: formValue.summary,
            picture: formValue.picture,
            video: formValue.video,
          },
          success: () => {
            this.props.dispatch(routerActions.goBack());
          },
          error: (msg) => {
            message.error(msg);
          },
        });
        api.run();
      }
    });
  }
  handChange(value) {
    const api = new Api({
      method: 'GET',
      path: `/tasks/${value}`,
      success: (json) => {
        this.setState({
          taskId: json.id,
        }, () => {
          this.initOrder();
          this.initFeedback();
          this.initPlan();
          this.initTaskInfo();
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  render() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const formValue = Object.assign(this.state.editRecord, this.state.taskInfo);
    const initialValue = formValue ? { ...formValue } : '';
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    const orderColumns = this.generatorOrderColumns();
    const feedColumns = this.generatorFeedBackColumns();
    const planColumns = this.generatorPlanColumns();
    return (
      <div className="next">
        <CommonBg
          title="典型案例修改"
          content={
            <div className="typical-case-add">
              <Form className="typical-case-add-form">
                <FormItem label="案例名称" {...formItemLayout}>
                  {getFieldDecorator('case_name', {
                    initialValue: initialValue ? initialValue.case_name : '',
                    rules: [
                      { required: true, message: '请选择案例名称' }
                    ]
                  })(
                    <Input placeholder="请输入案例名称" className="input" style={{ width: 840 }} />
                  )}
                </FormItem>
                <FormItem label="指挥调度任务" {...formItemLayout}>
                  {getFieldDecorator('task_name', {
                    initialValue: initialValue ? initialValue.task_name : '',
                    rules: [
                      { required: true, message: '请选择指挥调度任务' }
                    ]
                  })(
                    <Input disabled style={{ color: '#292929', width: 840 }} />
                  )}
                </FormItem>
                <FormItem label="任务时间" {...formItemLayout}>
                  {getFieldDecorator('create_time', {
                    initialValue: initialValue ? moment(initialValue.create_time).format('YYYY-MM-DD HH:mm:ss') : '',
                  })(
                    <Input disabled style={{ color: '#292929', width: 840 }} />
                  )}
                </FormItem>
                <FormItem label="参与人员" {...formItemLayout}>
                  {getFieldDecorator('law_executor', {
                    initialValue: initialValue ? initialValue.law_executor : '',
                  })(
                    <Input className="input" style={{ width: 840, color: '#292929' }} disabled />
                  )}
                </FormItem>
                <FormItem label="任务内容" {...formItemLayout}>
                  {getFieldDecorator('content ', {
                    initialValue: initialValue ? initialValue.content : '',
                  })(
                    <TextArea rows={4} className="input" style={{ width: 840, height: 150, color: '#292929' }} disabled />
                  )}
                </FormItem>
                <FormItem label="指令信息" {...formItemLayout}>
                  <Table
                    rowKey={record => record.id}
                    columns={orderColumns}
                    bordered
                    dataSource={this.state.orderList}
                    pagination={{
                      pageSize: PAGE_SIZE,
                      total: this.state.orderDataCount,
                      current: this.state.orderListPage,
                      onChange: this.onOrderListPageChange.bind(this)
                    }}
                  />
                </FormItem>
                <FormItem label="反馈信息" {...formItemLayout}>
                  <Table
                    rowKey={record => record.id}
                    columns={feedColumns}
                    bordered
                    dataSource={this.state.feedList}
                    pagination={{
                      pageSize: PAGE_SIZE,
                      total: this.state.feedDataCount,
                      current: this.state.feedListPage,
                      onChange: this.onFeedListPageChange.bind(this)
                    }}
                  />
                </FormItem>
                <FormItem label="启动预案信息" {...formItemLayout}>
                  <Table
                    rowKey={record => record.id}
                    columns={planColumns}
                    bordered
                    dataSource={this.state.planList}
                    pagination={{
                      pageSize: PAGE_SIZE,
                      total: this.state.planDataCount,
                      current: this.state.planListPage,
                      onChange: this.onPlanListPageChange.bind(this)
                    }}
                  />
                </FormItem>
                <FormItem label="指挥领导" {...formItemLayout}>
                  {getFieldDecorator('leader', {
                    initialValue: initialValue ? initialValue.leader : '',
                    rules: [
                      { required: true, message: '请输入指挥领导' }
                    ]
                  })(
                    <Input placeholder="请输入指挥领导" className="input" style={{ width: 840 }} />
                  )}
                </FormItem>
                <FormItem label="领导发言" {...formItemLayout}>
                  {getFieldDecorator('leader_speaking', {
                    initialValue: initialValue ? initialValue.leader_speaking : '',
                    rules: [
                      { required: true, message: '请输入领导发言' }
                    ]
                  })(
                    <TextArea rows={4} placeholder="请输入领导发言" className="input" style={{ width: 840, height: 150 }} />
                  )}
                </FormItem>
                <FormItem label="总结点评:" {...formItemLayout}>
                  {getFieldDecorator('summary', {
                    initialValue: initialValue ? parseInt(`${initialValue.summary}`, 10) : 0,
                    rules: [
                      { required: true, message: '请上传总结点评' }
                    ]
                  })(
                    <UploadAudio />
                  )}
                </FormItem>
                <FormItem label="图片" {...formItemLayout}>
                  {getFieldDecorator('picture', {
                    initialValue: initialValue ? initialValue.picture : '',
                    rules: [
                      { required: true, message: '请上传图片' }
                    ]
                  })(
                    <PicturesWall
                      initImg={initialValue.picture ? [initialValue.picture] : []}
                      isOpen={initialValue.picture !== undefined}
                    />
                  )}
                </FormItem >
                <FormItem label="视频" {...formItemLayout}>
                  {getFieldDecorator('video', {
                    initialValue: initialValue ? parseInt(`${initialValue.video}`, 10) : 0,
                    rules: [
                      { required: true, message: '请上传视频' }
                    ]
                  })(
                    <UploadVideo />
                  )}
                </FormItem >
              </Form>
              <div className="btns-wrap" style={{ marginTop: 100 }}>
                <Button className="btn" onClick={this.handCancel.bind(this)}>取消</Button>
                <Button className="btn" onClick={this.onEnter.bind(this)}>确认</Button>
              </div>
            </div>
          }
        />
      </div>
    );
  }
}
function mapStateToProps(state) {
  return {
    ...state.routing,
    ...state.mapReducer
  };
}

export default Form.create()(connect(mapStateToProps)(TypicalEdit));
